from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializer import *
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
import os
from rest_framework.generics import *


# Create your views here.
class BrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSer
    # 查找字段
    lookup_field = 'pk'
    # 地址里面传过来的关键字参数
    lookup_url_kwarg = 'pk'


# 上传图片的视图
class UploadLogoAPIView(APIView):

    # 前端en-upload 自己发送的post 请求
    def post(self,request):

        # 获取上传的数据
        file = request.FILES.get('file')
        print("前端上传的文件:", file, type(file))

        # file 身上有两个属性需要使用
        # file.file  当前的文件字节流 BytesIO
        # file.name  当前的文件的名字

        # 将文件字节流写入服务器
        filepath = os.path.join(settings.STATICFILES_DIRS[0],"images/logos/")
        print("静态文件路径:", filepath)

        filename = filepath + file.name

        with open(filename, "wb") as f:
            f.write(file.file.read())

        return Response({
            "code": "200",
            "msg": "上传成功",
            "file_path": "/static/images/logos/",
            "file_name": file.name
        }, status=200)


# 加载所有的频道数据
class ListChannelsAPIView(ListAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer


# 加载所有商品类别
class ListCateAPIView(ListAPIView):
    queryset = Cate.objects.all()
    serializer_class = CateSer


# 加载一个、更新一个、删除一个频道组视图
class ChannelAPIView(RetrieveUpdateDestroyAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'


# 加载一级类别
class FirstCateAPIView(ListAPIView):
    queryset = Cate.objects.filter(cid=None)
    serializer_class = CateSer


# 增加一个频道组的视图
class AddChannelView(APIView):
    def post(self,request):
        # 接受前端数据
        name = request.data.get("name")
        cate_name = request.data.get("cate_name")
        group_url = request.data.get("group_url")
        sequence = request.data.get("sequence")

        # 2.判断cate_name这个类别是否存在
        cate = Cate.objects.filter(name=cate_name).first()
        if not cate:
            return Response({"code":"400","msg":"添加的类别不存在"})

        # 3.组织下数据
        data = {
            "name": name,
            "cate": cate.id,
            "group_url": group_url,
            "sequence": sequence
        }
        # 4.实例化序列化器对象
        ser = GroupSer(data=data)

        if ser.is_valid():
            ser.save()

            return Response({"code":"200","msg":"添加频道组成功", "data": ser.data})
        else:
            return Response({"code":"400","msg":ser.errors_messages})


# SKU的视图
class SKUViewSet(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'


# SPU的视图
class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'


# 加载所有的类别
class SubCateViewSet(ModelViewSet):
    queryset = Cate.objects.all()
    serializer_class = CateSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    def retrieve(self, request, pk, *args, **kwargs):

        # 获取pk类别下的所有的二级类别
        sub_cate = self.get_queryset().filter(cid=pk)

        # 对于类别进行，序列化输出
        sub_cate_ser = self.get_serializer(sub_cate, many=True)

        return Response(sub_cate_ser.data)


# SPU规格的视图集
class SPUSpecificationViewSet(ModelViewSet):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecificationSer
    lookup_field = 'pk'
    lookup_url_kwarg = "pk"

    def create(self, request, *args, **kwargs):
        name = request.data['name']
        if SPUSpecification.objects.filter(name=name):
            return Response({'code':204,'msg':'该规格已存在'})
        else:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=201, headers=headers)


# 规格选项值的视图集
class SpecificationOptionViewSet(ModelViewSet):
    queryset = SpecificationOption.objects.all()
    serializer_class = SpecificationOptionSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"


class UploadSKUImageAPIView(APIView):
    def post(self, request):

        print("前端传入的数据:", request.data)

        # 1.获取文件
        file = request.data.get("file")

        # 2.处理相关的路径
        file_name = file.name
        static_path = "static/images/goods"
        file_path = os.path.join(settings.BASE_DIR, static_path)

        # 若目录不存在，则主动创建
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        # 获取图片的绝对路径
        sku_image = os.path.join(file_path, file_name)

        # 3.写入图片的字节流
        with open(sku_image, "wb") as f:
            f.write(file.file.read())

        # 4.返回响应
        return Response({
            "code": "200",
            "msg":"上传图片成功",
            "static_path":static_path
        })


# SKUImage的视图集
class SKUImageViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"

    # 重写create方法
    def create(self, request, *args, **kwargs):

        print("前端传入的数据:", request.data)

        # 1.获取前端传入的数据
        sku_id = request.data.get("sku")
        image = request.data.get("image")

        # 2.防止重复添加图片
        sku_image = SKUImage.objects.filter(sku_id=sku_id, image=image)

        if sku_image:
            return Response({"code": "400", "msg":"当前图片已存在，无法重复添加！"})

        # 3.正常存入数据库
        try:
            SKUImage.objects.create(sku_id=sku_id, image=image)

            return Response({
                "code":"200",
                "msg":"添加图片成功!"
            })

        except Exception as e:
            print("添加图片异常", e.args)
            return Response({"code":"400", "msg":"添加图片失败"})

    # 重写list方法
    # def list(self, request, *args, **kwargs):
    #     # 1.获取所有的商品图片
    #     sku_images = self.get_queryset()
    #     # 2.序列化
    #     sku_images_ser = self.get_serializer(sku_images, many=True)
    #
    #     # 3.处理一下序列化的数据
    #     my_data = []
    #     for i in sku_images_ser.data:
    #         i["image"] = i.get("image").split("/goods/imgs")[1]
    #         my_data.append(i)
    #     # 返回响应
    #     return Response(my_data)

    # 重写retrieve
    # def retrieve(self, request, pk, *args, **kwargs):
    #     sku_image = self.get_queryset().filter(id=pk).first()
    #
    #     sku_image_ser = self.get_serializer(sku_image)
    #
    #     my_data = sku_image_ser.data
    #
    #     my_data["image"] = os.path.join("/static",my_data.get("image").split("/static/")[1])
    #
    #     return Response(my_data)

    # 重写update方法
    # def update(self, request, pk, *args, **kwargs):
    #
    #     print("前端传入的数据:", request.data)
    #
    #     # 获取数据
    #     sku_id = request.data.get("sku")
    #     image = request.data.get("image")
    #
    #     # 查询待更新的对象
    #     sku_image = self.get_queryset().filter(id=pk).first()
    #
    #     # 更新
    #     sku_image.sku = sku_id
    #     sku_image.image = image
    #     sku_image.save()
    #
    #     return Response({"code":"200","msg":"更新成功！"})


# 生成七牛的token
from qiniu import Auth
# class QiNiuAPIView(APIView):
#
#     def get(self, request):
#
#         token = self.gen_token()
#
#         return Response({"code":"200", "token":token})
#
#     @staticmethod
#     def gen_token():
#         # 生成鉴权对象
#         auth = Auth("L4KBaBkhV52xMvErYgE6XbYDh57uy2qey2qppzRe", "L4KBaBkhV52xMvErYgE6XbYDh57uy2qey2qppzRe")
#         # 存储空间
#         bucket_name = "msdejx"
#
#         # 生成token
#         token